package br.com.emmis.tercons.controller;

import android.os.AsyncTask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import br.com.emmis.tercons.model.Donor;

/**
 * Created by vaner on 18/12/2014.
 */
public class DonationLoad {

    private static final String XML_URL = "http://www.trocandomilhas.com.br/tercons/donations.xml";
    private List<Donor> mDonors;
    private OnDonationLoadListener mListener;

    public DonationLoad() {
        mDonors = new ArrayList<Donor>();
        DownloadDonationXML dwXML = new DownloadDonationXML();
        dwXML.execute("");
    }

    public void setOnDonationLoadListener(OnDonationLoadListener onDonationLoadListener) {
        mListener = (OnDonationLoadListener) onDonationLoadListener;
    }

    public interface OnDonationLoadListener {
        public void onDonationsLoaded();
    }

    private class DownloadDonationXML extends AsyncTask<String, Void, List<Donor>> {

        @Override
        protected void onPostExecute(List<Donor> donors) {
            mDonors = donors;
            if(mDonors!= null && mDonors.size() > 0) {
                mListener.onDonationsLoaded();
            }
        }

        @Override
        protected List<Donor> doInBackground(String... strings) {
            List<Donor> donors = new ArrayList<Donor>();

            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(XML_URL);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                String line = EntityUtils.toString(httpEntity);

                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(new InputSource(new ByteArrayInputStream(line.getBytes("ISO-8859-1"))));

                NodeList nodes = doc.getElementsByTagName("donor");
                for (int i = 0; i < nodes.getLength(); i++) {
                    Element element = (Element) nodes.item(i);
                    int id = Integer.parseInt(element.getAttribute("id"));
                    String name = element.getTextContent();

                    Donor donor = new Donor(id, name);
                    donors.add(donor);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                return donors;
            }
        }

    }

    public List<Donor> getDonations() {
        return mDonors;
    }

    public Donor getRandomDonor() {
        int idx = new Random().nextInt(mDonors.size());
        return (mDonors.get(idx));
    }
}
